<template>
  <div class="upload-box">
    <el-upload
      v-model:file-list="epUploadFileList"
      action="#"
      :class="['upload', self_disabled ? 'disabled' : '', drag ? 'no-border' : '']"
      :multiple="false"
      :disabled="self_disabled"
      :limit="1"
      :http-request="handleHttpUpload"
      :before-upload="beforeUpload"
      :on-exceed="handleExceed"
      :on-success="uploadSuccess"
      :on-error="uploadError"
      :on-remove="deleteFile"
      :drag="drag"
      :accept="fileType.join(',')"
    >
      <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
      <div class="el-upload__text">拖动到这 或 <em>点击上传</em></div>
    </el-upload>
    <div class="el-upload__tip">
      <slot name="tip"></slot>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { Upload } from "@/api/interface/index";
import type { UploadProps, UploadUserFile, UploadRequestOptions } from "element-plus";
import { UploadFilled } from "@element-plus/icons-vue";
import { ref, inject, computed } from "vue";
import { CANROCNET } from "@/api/config/servicePort";
import { uploadApi } from "@/api/modules/system/upload";
import { ElNotification, formContextKey, formItemContextKey } from "element-plus";

defineOptions({
  name: "UploadFile"
});

interface UploadFileProps {
  modelValue: Upload.Result | undefined; // 上传成功后返回的文件信息
  api?: (params: any) => Promise<any>; // 上传附件的 api 方法，一般项目上传都是同一个 api 方法，在组件里直接引入即可 ==> 非必传
  drag?: boolean; // 是否支持拖拽上传 ==> 非必传（默认为 true）
  disabled?: boolean; // 是否禁用上传组件 ==> 非必传（默认为 false）
  fileSize?: number; // 附件大小限制 ==> 非必传（默认为 5M）
  fileType?: File.FileMimeType[]; // 附件类型限制 ==> 非必传（默认为 ["*/*"]）
  borderRadius?: string; // 组件边框圆角 ==> 非必传（默认为 8px）
}

// 接受父组件参数
const props = withDefaults(defineProps<UploadFileProps>(), {
  modelValue: () => ({}) as Upload.Result,
  drag: true,
  disabled: false,
  fileSize: 5,
  fileType: () => [
    "application/vnd.ms-excel",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    "application/msword",
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    "application/pdf"
  ],
  borderRadius: "8px"
});

const emit = defineEmits<{
  "update:modelValue": [value: Upload.Result | undefined];
}>();

// 获取 el-form 组件上下文
const formContext = inject(formContextKey, void 0);
// 获取 el-form-item 组件上下文
const formItemContext = inject(formItemContextKey, void 0);
// 判断是否禁用上传和删除
const self_disabled = computed(() => {
  return props.disabled || formContext?.disabled;
});

const epUploadFileList = ref<UploadUserFile[]>([
  {
    name: props.modelValue.name,
    url: CANROCNET + props.modelValue.url,
    status: "success",
    percentage: 100
  }
]);

/**
 * @description 附件上传
 * @param options upload 所有配置项
 * */
const handleHttpUpload = async (options: UploadRequestOptions) => {
  let formData = new FormData();
  formData.append("file", options.file);
  try {
    const api = props.api ?? uploadApi;
    const { data } = await api(formData);
    options.onSuccess(data);
  } catch (error) {
    options.onError(error as any);
  }
};

/**
 * @description 删除附件
 * */
const deleteFile = () => {
  emit("update:modelValue", undefined);
};

/**
 * @description 文件上传之前判断
 * @param rawFile 选择的文件
 * */
const beforeUpload: UploadProps["beforeUpload"] = rawFile => {
  const imgSize = rawFile.size / 1024 / 1024 < props.fileSize;
  const imgType = props.fileType.includes(rawFile.type as File.FileMimeType);
  if (!imgType)
    ElNotification({
      title: "温馨提示",
      message: "上传附件不符合所需的格式！",
      type: "warning"
    });
  if (!imgSize)
    setTimeout(() => {
      ElNotification({
        title: "温馨提示",
        message: `上传附件大小不能超过 ${props.fileSize}M！`,
        type: "warning"
      });
    }, 0);
  return imgType && imgSize;
};

/**
 * @description 文件数超出
 * */
const handleExceed = () => {
  ElNotification({
    title: "温馨提示",
    message: `当前最多只能上传 1 个附件，请移除后上传！`,
    type: "warning"
  });
};

/**
 * @description 附件上传成功
 * */
const uploadSuccess = (response: Upload.Result | undefined) => {
  if (!response) return;
  emit("update:modelValue", response);
  // 调用 el-form 内部的校验方法（可自动校验）
  formItemContext?.prop && formContext?.validateField([formItemContext.prop as string]);
  ElNotification({
    title: "温馨提示",
    message: "附件上传成功！",
    type: "success"
  });
};

/**
 * @description 附件上传错误
 * */
const uploadError = () => {
  ElNotification({
    title: "温馨提示",
    message: "附件上传失败，请您重新上传！",
    type: "error"
  });
};
</script>

<style scoped lang="scss">
@use "./index";
</style>
